<?php
namespace app\admin\controller;
use think\Controller;
use think\Request;
class Link extends Controller
{
	public function lst()
	{	
		$linkRes=db('Link')->paginate('10');
		$settitle=settitle('友情链接');
		$this->assign('settitle',$settitle);
		$this->assign('linkRes',$linkRes);
		return view();
	}
	public function add()
	{		
		if(request()->isPost())
		{
			$data=input('post.');
			//链接的处理
			if($data['link_url']&&stripos($data['link_url'],'http://')===false)
			{
				$data['link_url']='http://'.$data['link_url'];
			}
			//验证
    		$validate = validate('Link');
    		if(!$validate->check($data)){
			    $this->error($validate->getError());
			}
			//处理上传图片
			if($_FILES['logo']['tmp_name'])
			{
				$imgname='logo';
				$filename=IMG_UPLOADS.DS.'Link';
				$data['logo']=uploadsingle($imgname,$filename);
			}
			$add=db('Link')->insert($data);
			if($add)
			{
				$this->success('添加友情链接成功',url('lst'));
			}else
			{
				$this->error('添加友情链接失败');
			}
		}
		$settitle=settitle('友情链接');
		$this->assign('settitle',$settitle);
		return view();
	}

	public function edit()
	{	
		$id=input('id');
		if(request()->isPost())
		{	
			$data=input('post.');

			//链接的处理
			if($data['link_url']&&strpos($data['link_url'],'http://')===false)
			{
				$data['link_url']='http://'.$data['link_url'];
			}
			//验证
    		$validate = validate('Link');
    		if(!$validate->check($data)){
			    $this->error($validate->getError());
			}
			//处理上传图片
			if($_FILES['logo']['tmp_name'])
			{
				//修改时候先删除之前的友情链接图片(如果有)
				$this->delLinkimg($id);
				$imgname='logo';
				$filename=IMG_UPLOADS.DS.'link';
				$data['logo']=uploadsingle($imgname,$filename);
			}
			$save=db('Link')->update($data);
			if($save!==false)
			{
				$this->success('修改友情链接成功',url('lst'));
			}else
			{
				$this->error('修改友情链接失败');
			}
		}
		$links=db('Link')->find($id);
		$settitle=settitle('友情链接');
		$this->assign(
			array(
			'links'=>$links,
			'settitle'=>$settitle,
		)
	);
		return view();
	}

	public function del($id)
	{	
		$this->delLinkimg($id);
		$del=db('Link')->delete($id);
		if($del)
		{
			$this->success('删除友情链接成功',url('lst'));
		}else
		{
			$this->error('删除友情链接失败');
		}
	}

	//友情链接图片的删除
	public function delLinkimg($id)
	{
		//查询是否有友情链接图片 如果有则删除
		$imgurl=db('Link')->field('logo')->find($id);
		$imgurl=$imgurl['logo'];
		if(!empty($imgurl))
		{
			$fileurl=IMG_UPLOADS.DS.'Link';
			$filename=$fileurl.'\\'.$imgurl;
			if(file_exists($filename))
			{
				@unlink($filename);
			}
		}
	}
	//ajax异步修改友情链接启动状态
	public function ajaxchangelinkstatus()
	{
		$id=input('post.id');
		$link_status=db('link')->where('id',$id)->column('status');
		$link_status=$link_status[0];
		if($link_status==1)
		{
			$save=db('link')->where('id',$id)->setField('status',0);
			if($save)
			{
				echo 1;
			}
		}else
		{
			$save=db('link')->where('id',$id)->setField('status',1);
			if($save)
			{
				echo 2;
			}
		}

	}




}
